package com.cyh.listener;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class ContextLoaderListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        ServletContextListener.super.contextInitialized(sce);

        ServletContext servletContext = sce.getServletContext();

        //读取web.xml的全局参数
        String contextConfigLocation = servletContext.getInitParameter("contextConfigLocation");

        //ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
        ApplicationContext app = new ClassPathXmlApplicationContext(contextConfigLocation);
        //将spring的应用上下文对象存储到servletContext域中

        //servletContext.setAttribute("app", app);
        //统一地方设置获取
        WebApplicationContextUtil.setWebApplicationContext(servletContext, app);
        System.out.println("设置app监听器");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        ServletContextListener.super.contextDestroyed(sce);
    }
}
